package com.sudoku.solver;

import java.util.ArrayList;

import com.sudoku.board.Board;
import com.sudoku.board.Box;
import com.sudoku.board.Tile;

public class SoleCandidate extends Strategy{

	public SoleCandidate(Solver solver) {
		super(solver);
	}

	@Override
	public boolean solve(Board board) {
		stuck=true;
		for (Box box : board.getData()) {
			for (Tile tile : box.getData()) {
				if (soleCandidate(tile, board)) {
					stuck = false;
				}
			}
		}
		return stuck;
	}

	/**
	 * Check if this tile is the only one left in row or col
	 * 
	 * @param tile
	 * @return if change to tile was made
	 */
	private boolean soleCandidate(Tile tile, Board board) {
		if (tile.isBlank()) {
			final ArrayList<Integer> row = board.getBoardRow((int) ((ROWS_PER_BOX - 1 - tile.getBox().getCoords().y) * BOXES_PER_BOARD + ROWS_PER_BOX
					- 1 - tile.getCoords().y));
			final ArrayList<Integer> col = board.getBoardCol((int) (tile.getBox().getCoords().x * BOXES_PER_BOARD + tile.getCoords().x));

			// check col for sole tile
			solver.getBase().removeAll(col);
			if (solver.getBase().size() == 1) {
				solver.setNewTileData(tile, Board.IntToChar(solver.getBase().iterator().next()));
				return true;
			} else {
				solver.refillBase();
			}

			// check row for sole tile
			solver.getBase().removeAll(row);
			if (solver.getBase().size() == 1) {
				solver.setNewTileData(tile, Board.IntToChar(solver.getBase().iterator().next()));
				return true;
			} else {
				solver.refillBase();
			}
		}
		return false;
	}
}
